<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Auth;
use \App\Models\Log;
use Illuminate\Support\Facades\Route;

class OperateLog
{

    /**日志中间件
     * @param $request
     * @param Closure $next
     * @param null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {

        $user_id = 0;
        $ip=$this->getClientIp();
        if(Auth::guard("$guard")->check()) {
            $user_id = (int) Auth::guard("$guard")->user()->id;
        }

        $Agent=null;
        $referer=null;
        if(isset($_SERVER['HTTP_USER_AGENT']))
        {
            $Agent = $_SERVER['HTTP_USER_AGENT'];//客户端信息
        }
        if(isset($_SERVER['HTTP_REFERER']))
        {
            $referer=$_SERVER['HTTP_REFERER'];//访问上一页信息
        }
         $input = $request->except("_token");
        $action=Route::currentRouteAction();
        $action=str_replace("App\\Http\\Controllers\\", "", $action);
        $log =  new Log();
        $log->setAttribute('referer', $referer);
        $log->setAttribute('agent', $Agent);
        $log->setAttribute('user_id', $user_id);
        $log->setAttribute('action', $action);
        $log->setAttribute('client_ip', $ip);
        $log->setAttribute('url', $request->fullurl());
        $log->setAttribute('params', json_encode($input, JSON_UNESCAPED_UNICODE));
        $log->save();
        return $next($request);
    }
    public function getClientIp(){
        //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。

        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
        return $res;
        //dump(phpinfo());//所有PHP配置信息
    }
}
